﻿#include "MyFileOper.h"
#include <QByteArray>
#include <QString>
#include <QStringList>

MyFileOper::MyFileOper(void)
{
}

MyFileOper::~MyFileOper(void)
{
}

bool MyFileOper::WritePrivateProfileString_My(QString strSectionName, QString strKeyName, QString strValue, QString strFileName)
{
	bool bRet = false;
	if(strSectionName.isEmpty() || strKeyName.isEmpty() || strValue.isEmpty() || strFileName.isEmpty())
	{
		return bRet;
	}

	QFile			writeFile(strFileName);
	QTextStream		writeStream;
	QString			strSection;
	QString			strKey;
	QString			line;

	bool			bFindSection = false;
//	bool			bFindKey = false;
	qint64		SectPos = 0;
	qint64		KeyPos = 0;

	writeStream.setCodec("gbk");

	//是否找到了section
	strSection = QString("[" + strSectionName + "]");
	strKey = QString(strKeyName + "=");

	//文件不存在，则创建，且直接写入
	if(!QFile::exists(strFileName))
	{
		if(!writeFile.open(QFile::WriteOnly | QIODevice::Text))
		{
			return false;
		}
		//如果key和value不是null，才写内容
		if(!strKeyName.isEmpty() && !strValue.isEmpty())
		{
			writeStream.setDevice(&writeFile);
			writeStream<<strSection<<"\n";
			writeStream<<strKey<<strValue<<"\n";
			writeStream.flush();
			bRet = true;
		}
		writeFile.close();
		return bRet;
	}

	if (!writeFile.open(QIODevice::ReadWrite | QIODevice::Text))
	{
		bRet = false;
		return bRet;
	}

	writeStream.setDevice(&writeFile);

	/*
	while (!writeStream.atEnd())
	{
		line = writeStream.readLine();
		if (0 == line.indexOf(strSection))
		{
			SectPos = writeStream.pos();
			bFindSection = true;
			break;
		}
	}
    */

	KeyPos = writeFile.size();
	writeStream.seek(KeyPos);
	if (/*!bFindSection*/0 == strKey.compare(QString::fromLocal8Bit("0="), Qt::CaseInsensitive))
	{
		writeStream<<strSection<<"\n";
	}
	writeStream<<strKey<<strValue<<"\n";
	writeStream.flush();//写入流到文件
	writeFile.close();

	return true;
}

bool MyFileOper::WritePrivateProfileString_Replace(QString strSectionName, QString strKeyName, QString strValue, QString strFileName)
{
	bool bRet = false;
	if(strSectionName.isEmpty() || strKeyName.isEmpty() || strValue.isEmpty() || strFileName.isEmpty())
	{
		return bRet;
	}
	
	QFile			writeFile(strFileName);
	QTextStream		writeStream;
	QString			strSection;
	QString			strKey;
	QString			line;

	bool			bFindSection = false;
	bool			bFindKey = false;
	qint64		SectPos = 0;
	qint64		KeyPos = 0;

	writeStream.setCodec("gbk");

	//是否找到了section
	strSection = QString("[" + strSectionName + "]");
	strKey = QString(strKeyName + "=");

	//文件不存在，则创建，且直接写入
	if(!QFile::exists(strFileName))
	{
		if(!writeFile.open(QFile::WriteOnly | QIODevice::Text))
		{
			return false;
		}
		//如果key和value不是null，才写内容
		if(!strKeyName.isEmpty() && !strValue.isEmpty())
		{
			writeStream.setDevice(&writeFile);
			writeStream<<strSection<<"\r\n";
			writeStream<<strKey<<strValue<<"\r\n";
			writeStream.flush();
			bRet = true;
		}
		writeFile.close();
		return bRet;
	}

	if (!writeFile.open(QIODevice::ReadWrite | QIODevice::Text))
	{
		bRet = false;
		return bRet;
	}

	writeStream.setDevice(&writeFile);

	while (!writeStream.atEnd())
	{
		line = writeStream.readLine();
		if (0 == line.indexOf(strSection))
		{
			SectPos = writeStream.pos();
			bFindSection = true;
			break;
		}
	}

	if (bFindSection)
	{
		if (SectPos<writeFile.size() && !strKey.isEmpty())
		{
			do 
			{
				line.clear();
				KeyPos = writeStream.pos();
				line = QString(writeStream.readLine());
				if (0 == line.indexOf(strKey))
				{
					bFindKey = true;
					break;
				}
			} while(line.indexOf("[") != 0 && !writeStream.atEnd());
		}
	}

	if (writeStream.atEnd())
	{
		KeyPos = writeFile.size();
	}
	
	writeStream.seek(KeyPos);
	if (!bFindSection)
	{
		writeStream<<strSection<<"\r\n";
	}
	writeStream<<strKey<<strValue<<"\r\n";
	writeStream.flush();//写入流到文件
	writeFile.close();

	return true;
}


/*bool MyFileOper::WritePrivateProfileString(QString strSectionName, QString strKeyName, QString strValue, QString strFileName)
{
	bool ret = false;
	if(strSectionName.isEmpty() || strKeyName.isEmpty() || strValue.isEmpty() || strFileName.isEmpty())
	{
		return ret;
	}

	//是否找到了section
	bool flagFindSection = false;	
	int pos = 0;
	QString strSection("[" + strSectionName + "]");
	QString strKey(strKeyName + "=");

	//文件不存在，则创建，且直接写入
	if(!QFile::exists(strFileName))
	{
		QFile createFile(strFileName);
		if(!createFile.open(QFile::WriteOnly | QIODevice::Text))
		{
			return false;
		}
		//如果key和value不是null，才写内容
		if(!strKeyName.isEmpty() && !strValue.isEmpty())
		{
			QTextStream createStream(&createFile);
			createStream<<strSection<<"\r\n";
			createStream<<strKey<<strValue<<"\r\n";
			createStream.flush();
			ret = true;
		}
		createFile.close();
		return ret;
	}

	QFile readFile(strFileName);

	if (!readFile.open(QFile::ReadOnly | QIODevice::Text))
	{
		ret = false;
		return ret;
	}

	QFile writeFile(strFileName);

	//读入流和写入流
	//写入流文件在最后才WriteOnly打开
	QTextStream readStream(&readFile);
	QTextStream writeStream(&writeFile);
	readStream.setCodec("gbk");
	writeStream.setCodec("gbk");

	//查找每一行是否包含section
	while (!readStream.atEnd())
	{
		QString line(readStream.readLine());

		if (line.indexOf(strSection) != 0) //该行不包含section，直接写入流
		{
			writeStream<<line<<"\r\n";
		}
		else  
		{
			flagFindSection = true; //查到section
			ret = true;

			//key是null，则跳过该section,写入其余section
			if (!strKeyName.isEmpty())
			{
				do //跳过该section
				{
					line = QString(readStream.readLine());
				} while (line.indexOf("[") != 0 && !readStream.atEnd());

				if(readStream.atEnd())
				{
					break;
				}
				else //写入其余section
				{
					writeStream<<line<<"\r\n";
					while(!readStream.atEnd())
					{
						writeStream<<readStream.readLine()<<"\r\n";
					}
					break;
				}
			}

			writeStream<<line<<"\r\n";//section写入流
			line = QString(readStream.readLine());
			while(line.indexOf(strKey) != 0 && line.indexOf("[") != 0 && !readStream.atEnd())
			{
				writeStream<<line<<"\r\n";
				line = QString(readStream.readLine());
			}
			if (readStream.atEnd())//文件末尾，若value!=null则直接加上key
			{
				//直接加上
				if(!strValue.isEmpty())
				{
					writeStream<<strKey<<strValue<<"\r\n";
				}
			}
			else if(line.indexOf("[") == 0)//查到下一个section，若value!=null则在下一个section前直接加上key
			{
				if(strValue != NULL)
				{
					writeStream<<strKey<<strValue<<"\r\n";
				}
				writeStream<<line<<"\r\n";
				while(!readStream.atEnd()) //剩余行写入流中
				{
					writeStream<<readStream.readLine()<<"\r\n";
				}
				break;
			}
			else if(line.indexOf(strKeyName) == 0)//查到key，若value!=null则修改value
			{
				if(!strValue.isEmpty())
				{
					line = line.mid(0, line.indexOf("=") + 1) + strValue;
					writeStream<<line<<"\r\n";
				}
				while(!readStream.atEnd()) //剩余行写入流中
				{
					writeStream<<readStream.readLine()<<"\r\n";
				}
				break;
			}
		}
	}

	if(!flagFindSection)//若未查到该section，且key和value！=null，写入section和key=value
	{
		if (!strKeyName.isEmpty() && !strValue.isEmpty())
		{
			writeStream<<strSection<<"\r\n";
			writeStream<<strKey<<strValue<<"\r\n";
		}
	}
	readFile.close();

	//写打开文件
	if (!writeFile.open(QFile::WriteOnly | QIODevice::Text))
	{
		ret = false;
		return ret;
	}
	writeStream.flush();//写入流到文件

	writeFile.close();

	return ret;
}
*/
int MyFileOper::GetPrivateProfileStringList_My(QString strSectionName, QStringList &pReturnedStrLst, QString strFileName)
{
	pReturnedStrLst.clear();

	//文件不存在，返回默认字符串及其长度
	if (!QFile::exists(strFileName) || strSectionName.isEmpty())
	{
		return -1;
	}

	QString strSection("[" + strSectionName + "]");
//	QString strKey(strKeyName + "=");

	QFile readFile(strFileName);

	//打开失败，返回默认字符串及其长度
	if (!readFile.open(QFile::ReadOnly | QIODevice::Text))
	{
		return -1;
	}

	QTextStream readStream(&readFile);
	readStream.setCodec("gbk");

	QString line;

	while (!readStream.atEnd())
	{
		line.clear();
		line = readStream.readLine();
		if(line.indexOf(strSection, Qt::CaseInsensitive) == 0) //找到Section
		{
			while(!readStream.atEnd())
			{
				line = readStream.readLine();
				if (line.indexOf("[") != 0)
				{
					if (line.contains("=",Qt::CaseInsensitive))
					{
						pReturnedStrLst.append(line);
					}
				}else
				{
					break;
				}
			}
			break;
		}
	}
	readFile.close();
	
	return pReturnedStrLst.count();
	//未找到，返回默认值及其长度
}


int MyFileOper::GetPrivateProfileString_My(QString strSectionName, QString strKeyName, QString strDefault, QString &pReturnedStr, QString strFileName)
{
	//设置默认返回字符串
	if(strDefault.isEmpty())
	{
		strDefault = "";
	}
	//文件不存在，返回默认字符串及其长度
	if (!QFile::exists(strFileName) || strSectionName.isEmpty() || strKeyName.isEmpty())
	{
		pReturnedStr = strDefault;
		return -1;
	}

	QString strSection("[" + strSectionName + "]");
	QString strKey(strKeyName + "=");

	QFile readFile(strFileName);

	//打开失败，返回默认字符串及其长度
	if (!readFile.open(QFile::ReadOnly | QIODevice::Text))
	{
		pReturnedStr = strDefault;
		return -1;
	}

	QTextStream readStream(&readFile);
	readStream.setCodec("gbk");

	QString linenospace="";

	while (!readStream.atEnd())
	{
		QString line(readStream.readLine());
		linenospace=line;
		linenospace.replace(QRegExp("[\\s]+"), "");
		if(linenospace.indexOf(strSection,Qt::CaseInsensitive) == 0) //找到Section
		{
			line = readStream.readLine();
			linenospace=line;
			linenospace.replace(QRegExp("[\\s]+"), "");
			while(linenospace.indexOf(strKey) != 0 && line.indexOf("[") != 0 && !readStream.atEnd())
			{
				line = readStream.readLine();
				linenospace=line;
				linenospace.replace(QRegExp("[\\s]+"), "");
			}
			if (linenospace.indexOf(strKey) == 0) //找到Key
			{
				QString source(line.split("=").at(1));
				readFile.close();
				pReturnedStr = source;
				return pReturnedStr.length();
			}
		}
	}
	readFile.close();
	pReturnedStr = strDefault;
	return 0;
	//未找到，返回默认值及其长度
}

int MyFileOper::GetPrivateProfileString_My(QString strSectionName, QString strKeyName, QString strDefault, char * pReturnedValue, int size, QString strFileName)
{
	//设置默认返回字符串
	if(strDefault.isEmpty())
	{
		strDefault = "";
	}
	//文件不存在，返回默认字符串及其长度
	if (!QFile::exists(strFileName) || strSectionName.isEmpty() || strKeyName.isEmpty())
	{
		return StrCopy(strDefault, pReturnedValue, size);
	}

	QString strSection("[" + strSectionName + "]");
	QString strKey(strKeyName + "=");

	QFile readFile(strFileName);

	//打开失败，返回默认字符串及其长度
	if (!readFile.open(QFile::ReadOnly | QIODevice::Text))
	{
		return StrCopy(strDefault, pReturnedValue, size);
	}

	QTextStream readStream(&readFile);
	readStream.setCodec("gbk");

	QString linenospace="";

	while (!readStream.atEnd())
	{
		QString line(readStream.readLine());
		linenospace=line;
		linenospace.replace(QRegExp("[\\s]+"), "");
		if(linenospace.indexOf(strSection,Qt::CaseInsensitive) == 0) //找到Section
		{
			line = readStream.readLine();
			linenospace=line;
			linenospace.replace(QRegExp("[\\s]+"), "");
			while(linenospace.indexOf(strKey) != 0 && line.indexOf("[") != 0 && !readStream.atEnd())
			{
				line = readStream.readLine();
				linenospace=line;
				linenospace.replace(QRegExp("[\\s]+"), "");
			}
			if (linenospace.indexOf(strKey) == 0) //找到Key
			{
				QString source(line.split("=").at(1));
				readFile.close();
				return StrCopy(source, pReturnedValue, size);
			}
		}
	}
	readFile.close();
	//未找到，返回默认值及其长度
	return StrCopy(strDefault, pReturnedValue, size);
}

int MyFileOper::StrCopy(QString source, char *dest, int size)
{
	//QByteArray temp = source.toAscii();
	//拷贝字符串；
	//size合适，返回不加'\0'的字符串长度
	memset(dest, 0, size);
	if(source.toLocal8Bit().length() <= size - 1)
	{
		memcpy(dest, source.toLocal8Bit().data(), source.toLocal8Bit().length());
		return source.toLocal8Bit().length();
	}
	//拷贝字符串；
	//size过小，返回size-1
	else
	{
		memcpy(dest, source.toLocal8Bit().data(), size-1);
		dest[size - 1] = '\0';
		return size-1;
	}
}
